package com.nulstudio.sppm.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.nulstudio.sppm.Annotation.NormalJwt;
import com.nulstudio.sppm.Dao.CommodityMapper;
import com.nulstudio.sppm.Dao.InventoryEntryMapper;
import com.nulstudio.sppm.Dao.IssueInvoiceEntryMapper;
import com.nulstudio.sppm.Entities.*;
import com.nulstudio.sppm.Service.IssueInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@Controller
@RestController
@RequestMapping("/service/test/invoice")
public class IssueInvoiceController {
    @Autowired
    private IssueInvoiceService issueInvoiceService;
    @Autowired
    private IssueInvoiceEntryMapper issueInvoiceEntryMapper;
    @Autowired
    private InventoryEntryMapper inventoryEntryMapper;
    @Autowired
    private CommodityMapper commodityMapper;


    @NormalJwt
    @PostMapping(value = "/approveEntry",produces = "application/json;charset=UTF-8")
    public String fetchAll(@RequestBody Map<String,Object> map) {
        JSONObject json = new JSONObject();
        Boolean committed = (Boolean)map.get("committed");
        int id = (int)map.get("id");
        IssueInvoice invoice = issueInvoiceService.getInvoiceById(id);
        final int warehouseId = invoice.getWarehouseId();
        issueInvoiceService.setCommitted(id,committed);
        List<InvoiceEntry> list = issueInvoiceEntryMapper.getEntryById(id);
        for(InvoiceEntry entry : list){
            String name = entry.getName();
            final int nid = commodityMapper.getCommodityIdByName(name);
            final int quantity = entry.getQuantity();
            inventoryEntryMapper.transferEntry1(warehouseId,nid,quantity);
        }
        json.put("code",100);
        json.put("message", "");
        json.put("version",1);
        json.put("result", "");
        return json.toJSONString();
    }

    @NormalJwt
    @PostMapping(value ="/createEntry",produces = "application/json;charset=UTF-8")
    public String createEntry(@RequestBody Map<String,Object> map) {
        JSONObject json = new JSONObject();
        String[] properties = new String[]{"entries", "type","warehouseId"};
        for (String property : properties) {
            if (!map.containsKey(property)) {
                json.put("code", 400);
                json.put("message", property + " missed");
                json.put("version", 1);
                json.put("result", "");
                return json.toJSONString();
            }
        }
        String type = (String)map.get("type");
        int warehouseId = (int)map.get("warehouseId");
        List<LinkedHashMap> list = (List<LinkedHashMap>)map.get("entries");
        List<InvoiceEntry> entries = new ArrayList<>();
        int totalAmount = 0;
        float grossProfit = 0;
        for(LinkedHashMap request :list){
            InvoiceEntry entry = new InvoiceEntry();
            entry.setQuantity((int)request.get("quantity"));
            entry.setName((String)request.get("name"));
            entry.setNumber((int)request.get("number"));
            entry.setCostprice((float)request.get("costprice"));
            entry.setWholesalePrice((float)request.get("wholesalePrice"));
            entry.setRetailPrice((float)request.get("retailPrice"));
            if(type.equals("retail")){
                grossProfit += (entry.getCostprice() - entry.getRetailPrice())*entry.getQuantity();
            }else if(type.equals("wholesale")){
                grossProfit += (entry.getCostprice() - entry.getWholesalePrice())*entry.getQuantity();
            }
            totalAmount += entry.getQuantity();
            entries.add(entry);
        }
        IssueInvoice invoice = new IssueInvoice();
        invoice.setEntries((InvoiceEntry[]) entries.toArray());
        invoice.setCommited(false);
        invoice.setType(type);
        invoice.setDate(new Date());
        invoice.setTotalAmount(totalAmount);
        invoice.setGrossProfit(grossProfit);
        invoice.setWarehouseId(warehouseId);
        issueInvoiceService.createEntry(invoice);
        final int id = issueInvoiceService.getLastId();
        json.put("code", 0);
        json.put("message", "");
        json.put("version", 1);
        json.put("result", new invoicePost(id,invoice.getDate().toString()));
        return json.toJSONString();
    }

    @NormalJwt
    @PostMapping(value ="/modifyEntry",produces = "application/json;charset=UTF-8")
    public String modifyEntry(@RequestBody Map<String,Object> map) {
        JSONObject json = new JSONObject();
        Map<String,Object> map2 = new HashMap<>();
        map.put("id",map2.get("id"));
        deleteEntry(map2);
        createEntry(map);
        json.put("code", 0);
        json.put("message", "");
        json.put("version", 1);
        json.put("result","");
        return json.toJSONString();
    }

    @NormalJwt
    @PostMapping(value ="/deleteEntry",produces = "application/json;charset=UTF-8")
    public String deleteEntry(@RequestBody Map<String, Object> map){
        JSONObject json = new JSONObject();
        final String id = (String)map.get("id");
        issueInvoiceService.deleteWarehouse(Integer.parseInt(id));
        json.put("code", 0);
        json.put("message", "");
        json.put("result", "");
        json.put("version", 1);
        return json.toJSONString();
    }

}
